//
//  SearchClickViewController.m
//  CapriceMusic
//
//  Created by dllo on 16/1/8.
//  Copyright © 2016年 MYX. All rights reserved.
//

#import "SearchClickViewController.h"
#import "SearchViewController.h"
#import "SongerViewController.h"
#import "SearchTableViewCell.h"
#import "SongMenuTableViewCell.h"
#import "ActorTableViewCell.h"
#import "searchMVModel.h"
@interface SearchClickViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>
/**
 *  网络请求排序参数
 */
@property (nonatomic, copy) NSString *order;
@property (nonatomic, assign) NSInteger num;

@property (nonatomic, strong) UIView *myView;
@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) UIButton *makeTrue;
@property (nonatomic, strong) UIButton *cancel;
@property (nonatomic, strong) UITextField *textField;


//@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UIButton *relevanceButton;
@property (nonatomic, strong) UIButton *newestButton;
@property (nonatomic, strong) UIButton *maximumButton;
@property (nonatomic, strong) UITableView *tableView;
/**
 *  MV数组
 */
@property (nonatomic, strong) NSMutableArray *mvDataSouce;
@property (nonatomic, assign) NSInteger SegmentedNum;
/**
 *  buttonTitle
 */
@property (nonatomic, copy) NSString *buttonText;

@end

@implementation SearchClickViewController

/**
 *  当segmented为MV时 order关联最高为Default 最新上传为VideoPubDate 最多播放为TotalViews
    当segmented为悦单时 order关联最高为Default 最新上传为PlaylistId 最多播放为VideoNumber
    当segmented为艺人时 order关联最高为TotalViews 最多MV为TotalViews 最多粉丝为FanNumber
 */

- (void)viewDidLoad {
    [super viewDidLoad];
    /**
     *  关联最高
     */
    self.order = @"Default";
    self.num = 0;
    self.buttonText = KSearchMv;
    
    self.mvDataSouce = [NSMutableArray arrayWithCapacity:0];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setUpSearchBar];
    [self setUpTableView];
    [self getDataWithOrder:self.order withKeyWord:self.searchResult withOffset:self.num withUrl:KSearchMv];
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(receiveNotification:) name:@"collect" object:nil];
    
    [self getHeartRefresh];
    [self getFootRefresh];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    self.navigationController.navigationBarHidden = NO;
}
#pragma mark - tableView 
- (void)setUpTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 145, self.view.width, self.view.height - 145) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[SearchTableViewCell class] forCellReuseIdentifier:@"SearchTableViewCellIdentifier"];
    [self.tableView registerClass:[SongMenuTableViewCell class] forCellReuseIdentifier:@"SongMenuTableViewCellIdentifier"];
    [self.tableView registerClass:[ActorTableViewCell class] forCellReuseIdentifier:@"ActorTableViewCellIdentifier"];
    [self.view addSubview:self.tableView];
}

#pragma mark - tableViewDataSource 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.mvDataSouce.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 
    if (self.SegmentedNum == 0) {
        SearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchTableViewCellIdentifier"];
        if (self.mvDataSouce.count) {
            searchMVModel *mvModel = self.mvDataSouce[indexPath.row];
            [cell setSearchMvModel:mvModel];
        }
        return cell;
    }else if (self.SegmentedNum == 1) {
        SongMenuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SongMenuTableViewCellIdentifier"];
        if (self.mvDataSouce.count) {
            searchMVModel *mvModel = self.mvDataSouce[indexPath.row];
            [cell setMvModel:mvModel];
        }
        return cell;
    }else {
        ActorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ActorTableViewCellIdentifier"];
        if (self.mvDataSouce.count) {
            ActorModel *actorModel = self.mvDataSouce[indexPath.row];
            [cell setActorModel:actorModel];
        }
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.SegmentedNum == 0) {
        return (self.view.height - 145) / 5.2;
    }else if (self.SegmentedNum == 1){
        return (self.view.height - 145) / 3.2;
    }else {
        return (self.view.height - 145) / 5.3;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

#pragma mark - 网络请求
-(void)getDataWithOrder:(NSString *)order withKeyWord:(NSString *)keyWord withOffset:(NSInteger)offset withUrl:(NSString *)url {
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
    NSMutableArray *actorArr = [NSMutableArray arrayWithCapacity:0];
    [JEHNetWorkTool getWithUrl:url parameter:@{@"keyword":keyWord, @"order":order, @"area":@"ALL", @"videoType":@"ALL", @"singerType":@"ALL", @"access_token":@"web-b264c2fc75ab42e5Dtf5A1DWlU2.40e02.0", @"offset":[NSString stringWithFormat:@"%ld", (long)offset], @"size":@"20"} httpHeader:@{@"App-Id":@"10201029",@"Device-Id":@"5fc617ae1220d0969b23eaab4c8f02b5",@"Device-V":@"QW5kcm9pZF80LjQuNF8xMDgwKjE5MjBfMTEwMDA5MDAw"} responseType:ResponseTypeJSON success:^(id result) {
        for (NSString *str in [result allKeys]) {
            if ([str isEqualToString:@"videos"]) {
                [array addObjectsFromArray:result[@"videos"]];
            }else if ([str isEqualToString:@"playLists"]) {
                [array addObjectsFromArray:result[@"playLists"]];
            }else if ([str isEqualToString:@"artist"]) {
                [actorArr addObjectsFromArray:result[@"artist"]];
            }
        }
        for (NSDictionary *dic in array) {
            searchMVModel *mvModel = [[searchMVModel alloc] initWithDictionary:dic];
            [self.mvDataSouce addObject:mvModel];
        }
        if (actorArr.count) {
            for (NSDictionary *dic in actorArr) {
                ActorModel *actorModel = [[ActorModel alloc] initWithDictionary:dic];
                [self.mvDataSouce addObject:actorModel];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    } fail:^(NSError *error) {
        
    }];
}

- (void)getHeartRefresh {
    __weak typeof(self) weakSelf = self;
    [self.tableView addHeaderWithCallback:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.num = 0;
            [weakSelf.mvDataSouce removeAllObjects];
            [weakSelf getDataWithOrder:weakSelf.order withKeyWord:weakSelf.searchResult withOffset:weakSelf.num withUrl:weakSelf.buttonText];
            [weakSelf.tableView reloadData];
            [weakSelf.tableView headerEndRefreshing];
        });
    }];
}


- (void)getFootRefresh {
    __weak typeof(self) weakSelf = self;
    [self.tableView addFooterWithCallback:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.num += 20;
            [weakSelf getDataWithOrder:weakSelf.order withKeyWord:weakSelf.searchResult withOffset:weakSelf.num withUrl:weakSelf.buttonText];
            [weakSelf.tableView reloadData];
            [weakSelf.tableView footerEndRefreshing];
        });
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (self.SegmentedNum == 0) {
        DetailViewController *detailVC = [[DetailViewController alloc] init];
        searchMVModel *mvpageModel = self.mvDataSouce[indexPath.row];
        detailVC.appendingId = mvpageModel.ids;
        detailVC.type = @"VIDEO";
        [self.navigationController pushViewController:detailVC animated:YES];
    }else if (self.SegmentedNum == 1) {
        DetailViewController *detailVC = [[DetailViewController alloc] init];
        searchMVModel *mvpageModel = self.mvDataSouce[indexPath.row];
        detailVC.appendingId = mvpageModel.ids;
        detailVC.type = @"PLAYLIST";
        [self.navigationController pushViewController:detailVC animated:YES];
    }else {
        SongerViewController *songerVC = [[SongerViewController alloc] init];
        songerVC.actor = self.mvDataSouce[indexPath.row];
        ActorModel *actor = self.mvDataSouce[indexPath.row];
        songerVC.artistid = actor.ids.stringValue;
        [self.navigationController pushViewController:songerVC animated:YES];
    }
}
#pragma mark - searchBar
- (void)setUpSearchBar {
    self.myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 144)];
    self.myView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.myView];

    self.searchView = [[UIView alloc] initWithFrame:CGRectMake(10, 18, self.view.width - 60, 32)];
    _searchView.backgroundColor = [UIColor colorWithRed:221 / 255.0 green:221 / 255.0 blue:221 / 255.0 alpha:1.0];
    _searchView.layer.cornerRadius = 16;
    [self.myView addSubview:self.searchView];
    
    self.makeTrue = [UIButton buttonWithType:UIButtonTypeSystem];
    _makeTrue.frame = CGRectMake(self.view.width - 40, 25, 35, 17);

    [_makeTrue setTitleColor:[UIColor colorWithRed:221 / 255.0 green:221 / 255.0 blue:221 / 255.0 alpha:1.0] forState:UIControlStateNormal];
    [_makeTrue addTarget:self action:@selector(maketrue:) forControlEvents:UIControlEventTouchUpInside];
    [_makeTrue setTitle:@"取消" forState:UIControlStateNormal];
    [self.myView addSubview:self.makeTrue];
    
    UIImageView *fangDaJing = [[UIImageView alloc] initWithFrame:CGRectMake(15, 8, 17, 19)];
    fangDaJing.image = [UIImage imageNamed:@"Search"];
    [_searchView addSubview:fangDaJing];

    
    self.cancel = [UIButton buttonWithType:UIButtonTypeSystem];
    self.cancel.frame = CGRectMake(self.searchView.bounds.size.width - 40, 8, 18, 18);
    [self.cancel setImage:[[UIImage imageNamed:@"x"]  imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [self.cancel addTarget:self action:@selector(deleteKeyWord) forControlEvents:UIControlEventTouchDown];
    [_searchView addSubview:self.cancel];
    
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 8, 200, 17)];
    _textField.font = [UIFont systemFontOfSize:13];
    [_textField addTarget:self action:@selector(onEditing:) forControlEvents:UIControlEventAllEditingEvents];
    _textField.placeholder = @"输入艺人、MV或悦单名称";
    _textField.text = self.searchResult;
    [_searchView addSubview:self.textField];
    
    NSArray *array = @[@"MV", @"悦单", @"艺人"];
    UISegmentedControl *segmented = [[UISegmentedControl alloc] initWithItems:array];
    segmented.frame = CGRectMake(10, self.textField.bottom + 40, self.view.width - 20, 30);
    segmented.tintColor = [UIColor colorWithRed:30 / 255.0 green:195 / 255.0 blue:153 / 255.0 alpha:1.0];
    //当前选择的segmented
    segmented.selectedSegmentIndex = 0;
    [segmented addTarget:self action:@selector(segmentedDidButton:) forControlEvents:UIControlEventValueChanged];
    [self.myView addSubview:segmented];
    
    UILabel *sort = [[UILabel alloc] initWithFrame:CGRectMake(10, self.myView.bottom - 30, 30, 20)];
    sort.textColor = [UIColor colorWithRed:0.8421 green:0.8421 blue:0.8421 alpha:1.0];
    sort.text = @"排序:";
    sort.font = [UIFont systemFontOfSize:12];
    [self.myView addSubview:sort];
    
    self.relevanceButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.relevanceButton.frame = CGRectMake(sort.right + 10, sort.origin.y, 60, 20);
    [self.relevanceButton setTitle:@"关联最高" forState:UIControlStateNormal];
    self.relevanceButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [self.relevanceButton setTintColor:[UIColor colorWithRed:30 / 255.0 green:195 / 255.0 blue:153 / 255.0 alpha:1.0]];
    [self.relevanceButton addTarget:self action:@selector(relevanceDidButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.myView addSubview:self.relevanceButton];
    
    self.newestButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.newestButton.frame = CGRectMake(self.relevanceButton.right + 10, sort.origin.y, 60, 20);
    [self.newestButton setTitle:@"最新上传" forState:UIControlStateNormal];
    self.newestButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [self.newestButton setTintColor:[UIColor whiteColor]];
    [self.newestButton addTarget:self action:@selector(newestDidButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.myView addSubview:self.newestButton];
    
    self.maximumButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.maximumButton.frame = CGRectMake(self.newestButton.right + 10, sort.origin.y, 60, 20);
    [self.maximumButton setTitle:@"最多播放" forState:UIControlStateNormal];
    self.maximumButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [self.maximumButton setTintColor:[UIColor whiteColor]];
    [self.maximumButton addTarget:self action:@selector(maximumDidButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.myView addSubview:self.maximumButton];
}
/**
 *  搜索正在输入
 */
-(void)onEditing:(UITextField *)text {
    self.searchResult = self.textField.text;
    
    if (_textField.text.length != 0) {
        [self.mvDataSouce removeAllObjects];
        if (self.SegmentedNum == 0) {
            [self getDataWithOrder:self.order withKeyWord:self.searchResult withOffset:self.num withUrl:KSearchMv];
        }else if (self.SegmentedNum == 1){
            [self getDataWithOrder:self.order withKeyWord:self.searchResult withOffset:self.num withUrl:KSearchYueDan];
        }else {
            [self getDataWithOrder:self.order withKeyWord:self.searchResult withOffset:self.num withUrl:KSearchYiRen];
        }
    } else {
        [self.mvDataSouce removeAllObjects];
        [self.tableView reloadData];
    }
}
/**
 *  取消搜索
 */
-(void)maketrue:(UIButton *)sender {
    self.navigationController.navigationBarHidden = NO;
    SearchViewController *vc = [self.navigationController.viewControllers objectAtIndex:0];
    [self.navigationController popToViewController:vc animated:YES];
    
}
//点击屏幕空白处去掉键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.textField resignFirstResponder];
}

-(void)deleteKeyWord {
    _textField.text = nil;
    [self.mvDataSouce removeAllObjects];
    [self.tableView reloadData];
    [_makeTrue setTitle:@"取消" forState:UIControlStateNormal];
}

#pragma mark - relevance 
- (void)relevanceDidButton:(UIButton *)sender {
    //
    NSString *senderText = sender.titleLabel.text;
    [sender setTintColor:[UIColor colorWithRed:30 / 255.0 green:195 / 255.0 blue:153 / 255.0 alpha:1.0]];
    [self.newestButton setTintColor:[UIColor whiteColor]];
    [self.maximumButton setTintColor:[UIColor whiteColor]];
    if (self.SegmentedNum == 1 && [senderText isEqualToString:@"关联最高"]) {
        [self.mvDataSouce removeAllObjects];
        self.buttonText = KSearchYueDan;
        self.order = @"Default";
        [self getDataWithOrder:self.order withKeyWord:self.searchResult withOffset:self.num withUrl:KSearchYueDan];
    }else if (self.SegmentedNum == 2 && [senderText isEqualToString:@"关联最高"]) {
        [self.mvDataSouce removeAllObjects];
        self.buttonText = KSearchYiRen;
        self.order = @"TotalViews";
        [self getDataWithOrder:self.order withKeyWord:self.searchResult withOffset:self.num withUrl:KSearchYiRen];
    }else if ([senderText isEqualToString:@"关联最高"]) {
        [self.mvDataSouce removeAllObjects];
        self.buttonText = KSearchMv;
        self.order = @"Default";
        [self getDataWithOrder:self.order withKeyWord:self.searchResult withOffset:self.num withUrl:KSearchMv];
    }
}

#pragma mark - newestButton
/**
 *  最新上传
 */
- (void)newestDidButton:(UIButton *)sender {
    [sender setTintColor:[UIColor colorWithRed:30 / 255.0 green:195 / 255.0 blue:153 / 255.0 alpha:1.0]];
    [self.relevanceButton setTintColor:[UIColor whiteColor]];
    [self.maximumButton setTintColor:[UIColor whiteColor]];
    if ([sender.titleLabel.text isEqualToString:@"最新上传"]) {
        [self.mvDataSouce removeAllObjects];
        self.buttonText = KSearchMv;
        self.order = @"VideoPubDate";
        [self getDataWithOrder:self.order withKeyWord:self.searchResult withOffset:self.num withUrl:KSearchMv];
    }else if ([sender.titleLabel.text isEqualToString:@"最新创建"]) {
        [self.mvDataSouce removeAllObjects];
        self.buttonText = KSearchYueDan;
        self.order = @"PlaylistId";
        [self getDataWithOrder:self.order withKeyWord:self.searchResult withOffset:self.num withUrl:KSearchYueDan];
    }else if ([sender.titleLabel.text isEqualToString:@"最多MV"]) {
        [self.mvDataSouce removeAllObjects];
        self.buttonText = KSearchYiRen;
        self.order = @"TotalViews";
        [self getDataWithOrder:self.order withKeyWord:self.searchResult withOffset:self.num withUrl:KSearchYiRen];
    }
}

#pragma mark - maximumButton
/**
 *  最多播放
 */
- (void)maximumDidButton:(UIButton *)sender {
    [sender setTintColor:[UIColor colorWithRed:30 / 255.0 green:195 / 255.0 blue:153 / 255.0 alpha:1.0]];
    [self.relevanceButton setTintColor:[UIColor whiteColor]];
    [self.newestButton setTintColor:[UIColor whiteColor]];
    if (self.SegmentedNum == 1 && [sender.titleLabel.text isEqualToString:@"最多播放"]) {
        [self.mvDataSouce removeAllObjects];
        self.buttonText = KSearchYueDan;
        self.order = @"TotalViews";
        [self getDataWithOrder:self.order withKeyWord:self.searchResult withOffset:self.num withUrl:KSearchYueDan];
    }else if (self.SegmentedNum == 2 && [sender.titleLabel.text isEqualToString:@"最多粉丝"]) {
        [self.mvDataSouce removeAllObjects];
        self.buttonText = KSearchYiRen;
        self.order = @"FanNumber";
        [self.mvDataSouce removeAllObjects];
        [self getDataWithOrder:self.order withKeyWord:self.searchResult withOffset:self.num withUrl:KSearchYiRen];
    }else if ([sender.titleLabel.text isEqualToString:@"最多播放"]) {
        [self.mvDataSouce removeAllObjects];
        self.buttonText = KSearchMv;
        self.order = @"TotalViews";
        [self getDataWithOrder:self.order withKeyWord:self.searchResult withOffset:self.num withUrl:KSearchMv];
    }
}

#pragma mark - Segmented
- (void)segmentedDidButton:(UISegmentedControl *)sender {
    [self.relevanceButton setTintColor:[UIColor colorWithRed:30 / 255.0 green:195 / 255.0 blue:153 / 255.0 alpha:1.0]];
    [self.newestButton setTintColor:[UIColor whiteColor]];
    [self.maximumButton setTintColor:[UIColor whiteColor]];
   
    if (sender.selectedSegmentIndex == 0) {
        [self.mvDataSouce removeAllObjects];
        self.buttonText = KSearchMv;
        self.order = @"Default";
        self.SegmentedNum = sender.selectedSegmentIndex;
        [self.newestButton setTitle:@"最新上传" forState:UIControlStateNormal];
        [self.maximumButton setTitle:@"最多播放" forState:UIControlStateNormal];
        [self getDataWithOrder:self.order withKeyWord:self.searchResult withOffset:self.num withUrl:KSearchMv];
    }else if (sender.selectedSegmentIndex == 1) {
        [self.mvDataSouce removeAllObjects];
        self.buttonText = KSearchYueDan;
        self.order = @"Default";
        self.SegmentedNum = sender.selectedSegmentIndex;
        [self.newestButton setTitle:@"最新创建" forState:UIControlStateNormal];
        [self.maximumButton setTitle:@"最多播放" forState:UIControlStateNormal];
        [self getDataWithOrder:self.order withKeyWord:self.searchResult withOffset:self.num withUrl:KSearchYueDan];
    }else {
        [self.mvDataSouce removeAllObjects];
        self.buttonText = KSearchYiRen;
        self.SegmentedNum = sender.selectedSegmentIndex;
        [self.newestButton setTitle:@"最多MV" forState:UIControlStateNormal];
        [self.maximumButton setTitle:@"最多粉丝" forState:UIControlStateNormal];
//        self.order = @"TotalViews";
        self.order = @"Default";
        [self getDataWithOrder:self.order withKeyWord:self.searchResult withOffset:self.num withUrl:KSearchYiRen];
    }
}

#pragma mark - 通知
- (void)receiveNotification:(NSNotification *)messages {
    NSString *str = messages.object;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:str preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
